mapboxgl.accessToken = 'pk.eyJ1IjoibWlhb2J1YW8iLCJhIjoiY2t6bDY1ajVvMWN0NzJ1cGFoZ3libTEzcCJ9.8HouBrAuS5sfCOf2YcJ9zA';
mapboxgl.setRTLTextPlugin('https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.1.0/mapbox-gl-rtl-text.js');
var bounds = new mapboxgl.LngLatBounds(
    new mapboxgl.LngLat(65, 0),
    new mapboxgl.LngLat(140, 55)
)

var map = new mapboxgl.Map({
    container: 'mapChart',
    style: 'mapbox://styles/mapbox/light-v9',
    zoom: 8.6,
    center: [120.0828, 30.2327],
    maxBounds: bounds
});

map.addControl(new MapboxLanguage({
    defaultLanguage: 'zh'
}));

// 画点
let mapMarker = [];
function mapClear() {
    mapMarker.forEach((marker) => marker.remove())
    mapMarker = []
}
function mapRefresh() {
    mapClear()
    d3.json('/static/sites.json').then(d => {
        // 颜色映射
        let type = 'day'
        if(timeAnlysisType == 'year')
            type = 'year'
        if (timeAnlysisType == 'day')
            type = 'hour'
        if (timeAnlysisType == 'week')
            type = 'day'
        if (timeAnlysisType == 'month')
            type = 'month'
        AQIValue = mapData[type]
        // console.log(AQIValue)
        d.forEach(e => {
            if (AQIValue.hasOwnProperty(e.content.slice(0, 5))) {
                // console.log(mapData)
                e.color = topColor(AQIValue[e.content.slice(0, 5)])
            }
        });
        const markers = d

        // 标记点
        markers.forEach(function (marker) {
            if (marker.color != '#FFFFFF') {
                marker_on = new mapboxgl.Marker({
                    color: marker.color,
                    anchor: "center",
                    draggable: false,
                })
                    .setLngLat(marker.location)
                    .addTo(map);

                mapMarker.push(marker_on)

                const popup = new mapboxgl.Popup({ closeOnClick: false })
                    .setLngLat(marker.location)
                    .addTo(map);

                const el = marker_on.getElement();
                el.addEventListener('click', () => {
                    popup.setHTML(marker.content)
                    let siteNum = marker.content.split(' ')[0]
                    let jud = 1, ind = 0
                    for (ind = 0; ind < selectedSites.length; ind += 1) {
                        if (selectedSites[ind] == siteNum) {
                            jud = 0
                            break
                        }
                    }
                    if (jud) {
                        selectedSites.push(siteNum)
                    } else {
                        selectedSites.splice(ind, 1)
                    }
                    // console.log(selectedSites)
                    MDSaFCLU()
                    getTimeData()
                });
            }
        });
    })
}
